# !/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Time        : 2021/10/29 14:50
@Author      : Albert Darren
@Contact     : 2563491540@qq.com
@File        : support_vector_classifier.py
@Version     : Version 1.0.0
@Description : TODO
@Created By  : PyCharm
"""
from pandas import read_csv
from numpy import array
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC


def load_dataset(dataset_path, test_size=0.2):
    """
    读入CSV数据集，划分出属性数据集合和标记数据集
    :param dataset_path: CSV数据集路径
    :param test_size: 测试集大小，默认0.2
    :return: 训练集，测试集
    """
    breast_cancer_data = read_csv(dataset_path, header=0, names=list(range(1, 12)))
    attributes = array(breast_cancer_data.iloc[:, 1:10])
    labels = array(breast_cancer_data.iloc[:, -1])
    return train_test_split(attributes, labels, random_state=1, test_size=test_size)


def train(feature_train, target_train, kernel_type="linear"):
    """
    根据指定核函数训练SVC模型
    :param feature_train: 训练集特征
    :param target_train: 训练集目标
    :param kernel_type: 核函数类型
    linear：线性核函数
    poly：多项式核函数
    rbf：径向基核函数/高斯核
    sigmoid：sigmoid核函数
    precomputed：提前计算好核函数矩阵
    :return: 训练模型
    """
    svc_model = SVC(kernel=kernel_type)
    svc_model.fit(feature_train, target_train)
    return svc_model


if __name__ == '__main__':
    # 加载并划分数据集
    DATA_PATH = "../dataset/breastCancerData.csv"
    attr_train, attr_test, label_train, label_test = load_dataset(DATA_PATH)
    # 声明核函数字典
    kernel_dict = {"linear": "线性核函数", "poly": "多项式核函数",
                   "rbf": "径向基核函数", "sigmoid": "sigmoid核函数"}

    # 使用不同核函数依次训练模型并且评估平均精度
    for kernel, value in kernel_dict.items():
        model = train(attr_train, label_train, kernel_type=kernel)
        # 模型评估
        train_score = model.score(attr_train, label_train)
        test_score = model.score(attr_test, label_test)
        print("%sSVC训练集平均精度:" % value, train_score)
        print("%sSVC测试集集平均精度:" % value, test_score)
